#include "../include/evt_dispather.h"
#include "../include/timestamp.h"
#include "../include/ep_poller.h"
#include "../include/io_channel.h"

evt_dispather::evt_dispather()
:m_exit_flag(false),
m_owner_thread_id(boost::this_thread::get_id()),
m_ep_poller(new ep_poller())
{
    //ctor
}

evt_dispather::~evt_dispather()
{
    //dtor
}
x_bool  evt_dispather::is_owner_thread()
{
    return m_owner_thread_id == boost::this_thread::get_id();
}
void    evt_dispather::exit()
{
    m_exit_flag=true;
    weekup();
}
void    evt_dispather::weekup()
{
    //
}
void    evt_dispather::main_loop()
{
    BOOST_ASSERT(is_owner_thread());
    io_channel_raw_ptr_vec  channels;
    while( false == m_exit_flag){
        channels.clear();
        x_int32 poll_ret = m_ep_poller->get_event(channels,m_poll_timeout_ms);
        if(poll_ret > 0 ){
            for(x_uint32 i=0;i< channels.size();i++)
                channels[i]->handle_event();
        }
        exec_pending_functor();
    }
}

void    evt_dispather::exec_pending_functor()
{
    boost::mutex::scoped_lock   lock(m_functor_vec_mutex);
    if(m_pending_functors.size() > 0){
        for(x_uint32 i=0;i< m_pending_functors.size();i++)
            channels[i]();
    }
    m_pending_functors.clear();
}
void    evt_dispather::pending_functor_append(functor func)
{
    boost::mutex::scoped_lock   lock(m_functor_vec_mutex);
    m_pending_functors.push_back( func);
}
void    evt_dispather::run_functor(functor func)
{
    //
}

void    evt_dispather::run_functor_after(functor func, int milisecond)
{
    //
}

void    evt_dispather::run_functor_at(functor func,const timestamp& run_time)
{
    //
}

x_int32 evt_dispather::update_channel(io_channel*  channel)
{
    if(is_owner_thread()){
        return m_ep_poller-> update_channel(channel);
    }
}

x_int32 evt_dispather::update_subscribe_evt(io_channel*  channel)
{
    //
}
